package com.vip.jwt.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author VIP
 * 跨域
 */
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

    private static final String[] ORIGINS = new String[]{"GET", "POST", "PUT", "DELETE"};
    private static final String[] HEADERS = new String[]{""};

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods(ORIGINS)
                .allowedHeaders("*")
                .exposedHeaders(HEADERS)
                .maxAge(3600);
    }

    /**
     * 全局配置
     * 解决MybatisPlus的Long类型（雪花ID）返回前端精度丢失问题
     * 也可使用String类型作为ID，则不会出现精度丢失问题
     * @param converters
     */
//    @Override
//    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
//        // 全局配置序列化返回 JSON 处理
//        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
//        ObjectMapper objectMapper = converter.getObjectMapper();
//        SimpleModule simpleModule = new SimpleModule();
//        // Long类型转String类型
//        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
//        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
//        objectMapper.registerModule(simpleModule);
//        converter.setObjectMapper(objectMapper);
//        converters.add(converter);
//    }

}
